<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DBclass
 *
 * @author wlf
 */

if(!defined('TinyFW')) exit('Access denied!');

class tfDB {

    private static $instance = null;
    private $db_conn = null;
    private $db_engine = null;
    private $db_host = null;
    private $db_type = null;
    private $db_user = null;
    private $db_password = null;
    private $db_name = null;
    private $dsn = null;
    private $db_manager = null;
    private function  __construct() {
        
        include_once(SYS_PATH . "libs" . DS . "vendor" . DS . "Doctrine.class.php");
        spl_autoload_register(array('tfDoctrine','autoload'));

        if(tfConfig::getConfig("db_dsn") <> '') {
            $this->dsn = tfConfig::getConfig("db_dsn");
        } else {
            $this->db_host = tfConfig::getConfig("db_host");
            $this->db_type = tfConfig::getConfig("db_type");
            $this->db_name = tfConfig::getConfig("db_name");
            //set up dsn
            $this->dsn = $this->db_type . ":dbname=" . $this->db_name . ";host=". $this->db_host;
            //echo $this->dsn;
        }
       
        $this->db_user = tfConfig::getConfig("db_user");
        $this->db_password = tfConfig::getConfig("db_password");

        $dbh = new PDO($this->dsn, $this->db_user, $this->db_password);
        $this->db_conn = Doctrine_Manager::connection($dbh);
        $this->db_manager = Doctrine_Manager::getInstance();

        //Enable Validate
        $this->db_manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL);
        //echo $this->db_conn;
        
        
    }

    public static function singleton() {
        if(! tfConfig::getConfig('use_db')) {
            trigger_error("Please set the config  'use_db' to true if you want to use db engine! ", E_USER_ERROR);
            return true;
        }
        if(!isset (self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function _get_conn() {
        return $this->db_conn;
    }

    private function _get_dsn(){
        return $this->dsn;
    }

    private function _get_db_manager() {
        return $this->db_manager;
    }

    
    public static function getConn(){
        return self::singleton()->_get_conn();
    }

    public static function getDbManager(){
        return self::singleton()->_get_db_manager();
    }
    
    public static function  __callStatic($method_name,  $arguments) {
        return call_user_method_array($method_name, $this->singleton()->_get_conn(), $arguments);
    }
    
    
    
}
?>
